﻿using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Config;
using SuperSocket.SocketBase.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WPF_SocketServer_Demo.Interface;
using WPF_SocketServer_Demo.RequestInfo;
using WPF_SocketServer_Demo.Server;
using WPF_SocketServer_Demo.Session;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Tab;

namespace WPF_SocketServer_Demo.Base
{
    internal class DataReaderBase : ReactiveObject, IDataReader
    {
        private MyServer _server;

        [Reactive]
        public bool Initialized { get; private set; }

        [Reactive]
        public bool Connected { get; private set; }

        [Reactive]
        public string Message { get; private set; }

        public IObservable<string> MessageObservable { get; }

        public string Data { get; set; }
        public byte[] UsartSendBuff { get; private set; } = new byte[350];

        public DataReaderBase()
        {
            MessageObservable = this.WhenAnyValue(p => p.Message);
        }

        public bool Init()
        {
            try
            {
                _server = new MyServer();
                _server.Setup(new ServerConfig
                {
                    Name = "MyServer",
                    Ip = "Any",
                    Port = 2012
                });

                _server.NewSessionConnected += (session) =>
                {
                    Message = $"New session connected: {session.RemoteEndPoint}";
                    appServer_NewSessionConnected(session);
                };

                _server.SessionClosed += (session, reason) =>
                {
                    Message = $"Session closed: {session.RemoteEndPoint}";
                };

                _server.NewRequestReceived += (session, requestInfo) =>
                {
                    appServer_NewRecived(session, requestInfo);
                };

                _server.Start();
                Initialized = true;
                Connected = true;
                return true;
            }
            catch
            {
                Initialized = false;
                Connected = false;
                return false;
            }
        }

        

    private void appServer_NewSessionConnected(MySession session)
    {
        //有新连接的时候,添加记录  session.RemoteEndPoint属性获取当前session的ip和端口号
        //AppSession 代表一个和客户端的逻辑连接，基于连接的操作应该定于在该类之中。
        //你可以用该类的实例发送数据到客户端，接收客户端发送的数据或者关闭连接。
        session.Send("Welcome to SuperSocket!");

        try
        {
            //利用线程不断发送数据
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    //todo...发送数据
                    Stm32DataSend(session);
                    Task.Delay(100).Wait();
                }
            });
        }
        catch (Exception ex)
        {
            Console.WriteLine("发送超时");
        }

    }

    public void Stm32DataSend(MySession session)
    {
        // 清空 UsartSendBuff 数组
        Array.Clear(UsartSendBuff, 0, UsartSendBuff.Length);

        // 设置指定索引的值
        UsartSendBuff[0] = 150;
        UsartSendBuff[21] = 1;
        UsartSendBuff[99] = 2;
        UsartSendBuff[100] = 1;

        UsartSendBuff[148] = 0x0D;
        UsartSendBuff[149] = 0x0A;
        session.Send(UsartSendBuff, 0, 150);
    }

        /// <summary>
        ///0x40, 0x49, 0x0f, 0xd0, // float 1 (SubBLM_AMP[c1])
        ///0x3f, 0x80, 0x00, 0x00, // float 2 (SubBLM_PHA[c1])
        ///0x41, 0x20, 0x00, 0x00, // float 3 (SubBLM_AMP[c2])
        ///0x40, 0x40, 0x00, 0x00, // float 4 (SubBLM_PHA[c2])
        ///0x00, 0x00, 0x00, 0x01, // int 1 (SubSIN_SUM[c1])
        ///0x00, 0x00, 0x00, 0x02, // int 2 (SubCOS_SUM[c1])
        ///0x00, 0x00, 0x00, 0x03, // int 3 (SubSIN_SUM[c2])
        ///0x00, 0x00, 0x00, 0x04  // int 4 (SubCOS_SUM[c2])
        ///40 49 0F D0
        ///01 26 26 26 26 00 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 04 FF 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// </summary>
        /// <param name="session"></param>
        /// <param name="requestInfo"></param>
        /// 

        private void appServer_NewRecived(MySession session, DTRequestInfo requestInfo) 
        {
            DoAnalysis(requestInfo.Body);
            session.Send(requestInfo.Key);
        }

        int i = 0;
        private void DoAnalysis(byte[] receiveBytes)
        {
            string v = BitConverter.ToString(receiveBytes, 0, receiveBytes.Length);
            Console.WriteLine(receiveBytes.Length);
        }



        public void Close()
        {
            if (_server != null)
            {
                _server.Stop();
                _server = null;
                Initialized = false;
                Connected = false;
                Message = "Server stopped.";
            }
        }

        public bool CheckConnection()
        {
            // Implement connection checking logic here
            throw new NotImplementedException();
        }
    }
}
